﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using System.IO;
using Telerik.WinControls.UI;
using Telerik.WinControls.Data;
using log4net;
using System.IO.Compression;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections;
using System.Text.RegularExpressions;
using Bytescout.BarCodeReader;
using System.Runtime.InteropServices;

namespace QuanLyNhaSach
{
    public partial class frmHoaDonBanLe : Telerik.WinControls.UI.RadForm
    {
        //Tao Parttern Seleton
        static frmHoaDonBanLe doituong = null;
        public static frmHoaDonBanLe TaoDoiTuong()
        {
            if (doituong == null)
                doituong = new frmHoaDonBanLe();
            return doituong;
        }

        public frmHoaDonBanLe()
        {
            InitializeComponent();
            logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        }
        #region "Khai bao bien"
        public event EventHandler xoahang;
        private ILog logger;
        sv_QuanLyNhaSach.AdapterClient service = new sv_QuanLyNhaSach.AdapterClient();        
        int vitri;        
        string mahang;
        string tenhang;
        string dongia;
        string soluong;
        string khuyenmai;
        string thanhtien;

        double tienDaDua = 0;
        double tienConLai = 0;
        float chietkhau;
        double tienthue = 0;
        double tongtien = 0;
        double tongtienhang = 0;
        public string manv = frmDangNhap.maNV_FromDangNhap;
        ArrayList Test_DMKho;        
        KiemTraBatLoi batloi = new KiemTraBatLoi();        
        #endregion

        #region "Ham chuyen so thanh chu"
        private static string Chu(string gNumber)
        {
            string result = "";
            switch (gNumber)
            {
                case "0":
                    result = "không";
                    break;
                case "1":
                    result = "một";
                    break;
                case "2":
                    result = "hai";
                    break;
                case "3":
                    result = "ba";
                    break;
                case "4":
                    result = "bốn";
                    break;
                case "5":
                    result = "năm";
                    break;
                case "6":
                    result = "sáu";
                    break;
                case "7":
                    result = "bảy";
                    break;
                case "8":
                    result = "tám";
                    break;
                case "9":
                    result = "chín";
                    break;
            }
            return result;
        }
        private static string Donvi(string so)
        {
            string Kdonvi = "";

            if (so.Equals("1"))
                Kdonvi = "";
            if (so.Equals("2"))
                Kdonvi = "nghìn";
            if (so.Equals("3"))
                Kdonvi = "triệu";
            if (so.Equals("4"))
                Kdonvi = "tỷ";
            if (so.Equals("5"))
                Kdonvi = "nghìn tỷ";
            if (so.Equals("6"))
                Kdonvi = "triệu tỷ";
            if (so.Equals("7"))
                Kdonvi = "tỷ tỷ";

            return Kdonvi;
        }
        private static string Tach(string tach3)
        {
            string Ktach = "";
            if (tach3.Equals("000"))
                return "";
            if (tach3.Length == 3)
            {
                string tr = tach3.Trim().Substring(0, 1).ToString().Trim();
                string ch = tach3.Trim().Substring(1, 1).ToString().Trim();
                string dv = tach3.Trim().Substring(2, 1).ToString().Trim();
                if (tr.Equals("0") && ch.Equals("0"))
                    Ktach = " không trăm lẻ " + Chu(dv.ToString().Trim()) + " ";
                if (!tr.Equals("0") && ch.Equals("0") && dv.Equals("0"))
                    Ktach = Chu(tr.ToString().Trim()).Trim() + " trăm ";
                if (!tr.Equals("0") && ch.Equals("0") && !dv.Equals("0"))
                    Ktach = Chu(tr.ToString().Trim()).Trim() + " trăm lẻ " + Chu(dv.Trim()).Trim() + " ";
                if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi " + Chu(dv.Trim()).Trim() + " ";
                if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && dv.Equals("0"))
                    Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi ";
                if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && dv.Equals("5"))
                    Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi lăm ";
                if (tr.Equals("0") && ch.Equals("1") && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = " không trăm mười " + Chu(dv.Trim()).Trim() + " ";
                if (tr.Equals("0") && ch.Equals("1") && dv.Equals("0"))
                    Ktach = " không trăm mười ";
                if (tr.Equals("0") && ch.Equals("1") && dv.Equals("5"))
                    Ktach = " không trăm mười lăm ";
                if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi " + Chu(dv.Trim()).Trim() + " ";
                if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && dv.Equals("0"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi ";
                if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi lăm ";
                if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm mười " + Chu(dv.Trim()).Trim() + " ";

                if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && dv.Equals("0"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm mười ";
                if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm mười lăm ";

            }


            return Ktach;

        }
        public static string So_chu(double gNum)
        {
            if (gNum == 0)
                return "Không đồng";

            string lso_chu = "";
            string tach_mod = "";
            string tach_conlai = "";
            double Num = Math.Round(gNum, 0);
            string gN = Convert.ToString(Num);
            int m = Convert.ToInt32(gN.Length / 3);
            int mod = gN.Length - m * 3;
            string dau = "[+]";

            // Dau [+ , - ]
            if (gNum < 0)
                dau = "[-]";
            dau = "";

            // Tach hang lon nhat
            if (mod.Equals(1))
                tach_mod = "00" + Convert.ToString(Num.ToString().Trim().Substring(0, 1)).Trim();
            if (mod.Equals(2))
                tach_mod = "0" + Convert.ToString(Num.ToString().Trim().Substring(0, 2)).Trim();
            if (mod.Equals(0))
                tach_mod = "000";
            // Tach hang con lai sau mod :
            if (Num.ToString().Length > 2)
                tach_conlai = Convert.ToString(Num.ToString().Trim().Substring(mod, Num.ToString().Length - mod)).Trim();

            ///don vi hang mod 
            int im = m + 1;
            if (mod > 0)
                lso_chu = Tach(tach_mod).ToString().Trim() + " " + Donvi(im.ToString().Trim());
            /// Tach 3 trong tach_conlai

            int i = m;
            int _m = m;
            int j = 1;
            string tach3 = "";
            string tach3_ = "";

            while (i > 0)
            {
                tach3 = tach_conlai.Trim().Substring(0, 3).Trim();
                tach3_ = tach3;
                lso_chu = lso_chu.Trim() + " " + Tach(tach3.Trim()).Trim();
                m = _m + 1 - j;
                if (!tach3_.Equals("000"))
                    lso_chu = lso_chu.Trim() + " " + Donvi(m.ToString().Trim()).Trim();
                tach_conlai = tach_conlai.Trim().Substring(3, tach_conlai.Trim().Length - 3);

                i = i - 1;
                j = j + 1;
            }
            if (lso_chu.Trim().Substring(0, 1).Equals("k"))
                lso_chu = lso_chu.Trim().Substring(10, lso_chu.Trim().Length - 10).Trim();
            if (lso_chu.Trim().Substring(0, 1).Equals("l"))
                lso_chu = lso_chu.Trim().Substring(2, lso_chu.Trim().Length - 2).Trim();
            if (lso_chu.Trim().Length > 0)
                lso_chu = dau.Trim() + " " + lso_chu.Trim().Substring(0, 1).Trim().ToUpper() + lso_chu.Trim().Substring(1, lso_chu.Trim().Length - 1).Trim() + " đồng chẵn.";

            return lso_chu.ToString().Trim();

        }
        #endregion        

        private void frmHoaDonBanLe_Load(object sender, EventArgs e)
        {
            //set ngay thang hien tai
            dtpNgayBan.Value = DateTime.Now;     
            //Load ma hang
            loadMahang();
            //Load Kho Hang
            Load_DSKho();
            //Chọn mặc định Quầy 1
            cbb_Quay.SelectedIndex = 0;
            //focus vao so chung tu
            txtChungTu.Focus();
        }

        private void loadMahang()
        {
            //---------------------------
            try
            {
                //Chinh do dai cua cac cot trong muiltcombobox
                RadMultiColumnComboBoxElement multiColumnComboElement = this.cmbMaHang.MultiColumnComboBoxElement;
                multiColumnComboElement.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multiColumnComboElement.DropDownMinSize = new Size(300, 200);

                DataSet ds = new DataSet();
                ds.ReadXml(new StringReader(service.selectqueryByText("select mamh,tenmh,DonGiaLe,KhuyenMai from MatHang")));
                if (ds.Tables.Count > 0)
                {
                    cmbMaHang.DataSource = ds.Tables[0];
                    cmbMaHang.DisplayMember = "mamh";
                    cmbMaHang.ValueMember = "mamh";
                    cmbMaHang.SelectedIndex = -1;
                }
            }
            catch (Exception ex)
            {
                logger.Error("Lỗi Load mat hang: " + ex.Message);
            }
            FilterDescriptor des_mh = new FilterDescriptor(this.cmbMaHang.DisplayMember, FilterOperator.StartsWith, string.Empty);
            cmbMaHang.EditorControl.FilterDescriptors.Add(des_mh);
        }
        private void Load_DSKho()
        {
            //---------------------------
            try
            {
                //Chinh do dai cua cac cot trong muiltcombobox
                RadMultiColumnComboBoxElement multiColumnComboElement = this.mcbb_KhoHang.MultiColumnComboBoxElement;
                multiColumnComboElement.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multiColumnComboElement.DropDownMinSize = new Size(200, 150);

                DataSet ds = new DataSet();
                ds.ReadXml(new StringReader(service.LayDS_Kho()));
                if (ds.Tables.Count > 0)
                {
                    Test_DMKho = new ArrayList();
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        Test_DMKho.Add(ds.Tables[0].Rows[i]["TenKho"].ToString().Trim());
                    }

                    mcbb_KhoHang.DataSource = ds.Tables[0];
                    mcbb_KhoHang.DisplayMember = "TenKho";
                    mcbb_KhoHang.ValueMember = "MaKho";
                    mcbb_KhoHang.SelectedIndex = -1;
                }
            }
            catch (Exception ex)
            {
                logger.Error("Lỗi Load mat hang: " + ex.Message);
            }
            FilterDescriptor des_mh = new FilterDescriptor(this.mcbb_KhoHang.DisplayMember, FilterOperator.StartsWith, string.Empty);
            cmbMaHang.EditorControl.FilterDescriptors.Add(des_mh);
        }
        private object Decompress(byte[] gzip)
        {
            using (DeflateStream stream = new DeflateStream(new MemoryStream(gzip), CompressionMode.Decompress))
            {
                const int size = 4096;
                byte[] buffer = new byte[size];
                using (MemoryStream memory = new MemoryStream())
                {
                    int count = 0;
                    do
                    {
                        count = stream.Read(buffer, 0, size);
                        if (count > 0)
                        {
                            memory.Write(buffer, 0, count);
                        }
                    }
                    while (count > 0);
                    var dataOut = memory.ToArray();
                    MemoryStream _MemoryStreamb = new MemoryStream(dataOut);
                    BinaryFormatter _BinaryFormatterb = new BinaryFormatter();
                    // Serializes an object, or graph of connected objects, to the given stream.
                    return _BinaryFormatterb.Deserialize(_MemoryStreamb);
                }
            }
        }
        private void cmbMaHang_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmbMaHang.Text.Trim() == "")
                {
                    txtSoluong.Text = "1";
                    txtTenHang.Text = "";
                    txtDonGia.Text = "0";
                    txtKhuyenMai.Text = "0";
                    txtThanhTien.Text = "0";
                    txtTienChu.Text = "Không đồng chẳn";
                    pictureBox1.Image = null;
                }
                else
                {
                    txtTenHang.Text = cmbMaHang.EditorControl.Rows[cmbMaHang.SelectedIndex].Cells["TenMH"].Value.ToString().Trim();
                    txtDonGia.Text =  cmbMaHang.EditorControl.Rows[cmbMaHang.SelectedIndex].Cells["DonGiaLe"].Value.ToString().Trim();
                    txtKhuyenMai.Text = cmbMaHang.EditorControl.Rows[cmbMaHang.SelectedIndex].Cells["KhuyenMai"].Value.ToString().Trim();
                    //Lay hinh dua len Picturebox
                    byte[] hinh = service.Layhinh(cmbMaHang.SelectedValue.ToString().Trim());
                    if (hinh != null)
                    {
                        hinh = (byte[])Decompress(hinh);
                        pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
                        pictureBox1.Image = Image.FromStream(new MemoryStream(hinh));
                    }
                    else
                    {
                        pictureBox1.SizeMode = PictureBoxSizeMode.Normal;
                        pictureBox1.Image = global::QuanLyNhaSach.Properties.Resources.close2;
                    }

                    //DataSet ds_hang = new DataSet();
                    //ds_hang.ReadXml(new StringReader(service.selectqueryByText("select mamh,tenmh,DonGiaLe,khuyenmai,hinh from MatHang where mamh='" + cmbMaHang.SelectedValue.ToString() + "'")));
                    //if (ds_hang.Tables.Count > 0)
                    //{
                    //    DataTable tblHang = ds_hang.Tables[0];
                    //    if (tblHang.Rows[0][2].ToString().Contains(".0000") == true)
                    //    {
                    //        tblHang.Rows[0][2] = tblHang.Rows[0][2].ToString().Replace(".0000", "");
                    //    }
                    //    if (cmbMaHang.SelectedIndex != -1)
                    //    {
                    //        txtTenHang.Text = tblHang.Rows[0][1].ToString();
                    //        txtDonGia.Text = tblHang.Rows[0][2].ToString();
                    //        txtKhuyenMai.Text = (double.Parse(tblHang.Rows[0][3].ToString()) * 100).ToString();
                    //    }
                    //}
                    ////load hinh vao picturebox
                    //pictureBox1.Image = Image.FromStream(new MemoryStream(service.Layhinh(cmbMaHang.SelectedValue.ToString().Trim())));
                }
            }
            catch (Exception ex)
            {
                logger.Error("Ham cmbMaHang_SelectedIndexChanged:" + ex.Message);
            }
        }
        
        private void txtSoluong_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txtSoluong.Text.Length != 0)
                {
                    txtSoluong.Text = double.Parse(txtSoluong.Text).ToString("#,##0");
                    double thanhtien = double.Parse(txtSoluong.Text) * double.Parse(txtDonGia.Text) - double.Parse(txtSoluong.Text) * double.Parse(txtDonGia.Text) * float.Parse(txtKhuyenMai.Text) / 100;
                    txtThanhTien.Text = thanhtien.ToString("#,##0");
                }
                txtSoluong.SelectionStart = txtSoluong.Text.Length;
            }
            catch (Exception ex)
            {
                logger.Error("Ham txtSoluong_TextChanged: "+ex.Message);
            }
        }

        private void TextBoxKeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }
        private bool ktmh(string mamh)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(service.selectqueryByText("select mamh from mathang where mamh like'"+mamh.Trim()+"'")));
            if (ds.Tables.Count>0)
            {
                return true;
            }
            return false;
        }
        private void btnNhan_Click(object sender, EventArgs e)
        {
            try
            {
                errorProvider1.Clear();
                txtDonGia.Enabled = false;
                if (txtChungTu.Text.Trim() == "")
                {
                    errorProvider1.SetError(txtChungTu, "Chưa nhập thông tin Số Chứng Từ.");
                    txtChungTu.Focus();
                    return;
                }
                if (mcbb_KhoHang.Text.Trim() == "")
                {
                    errorProvider1.SetError(mcbb_KhoHang, "Chưa chọn kho hàng.");
                    mcbb_KhoHang.Focus();
                    return;
                }
                if (Test_DMKho.Contains(mcbb_KhoHang.Text.Trim()) == false)
                    if (cmbMaHang.Text.Trim() == "")
                    {
                        errorProvider1.SetError(cmbMaHang, "Kho hàng không hợp lệ.");
                        cmbMaHang.Focus();
                        return;
                    }
                if (ktmh(cmbMaHang.Text) == false)
                {
                    errorProvider1.SetError(cmbMaHang, "Mặt hàng không hợp lệ");
                    cmbMaHang.Focus();
                    return;
                }
                if (txtSoluong.Text.Trim() == "" || double.Parse(txtSoluong.Text) == 0)
                {
                    errorProvider1.SetError(txtSoluong, "Số lượng không được để trống và là số nguyên không âm.");
                    txtSoluong.Focus();
                    return;
                }
                if (txtDonGia.Text.Trim() == "" || double.Parse(txtDonGia.Text) == 0)
                {
                    errorProvider1.SetError(txtDonGia, "Đơn giá không được để trống và là số nguyên không âm.");
                    txtDonGia.Enabled = true;
                    txtDonGia.Focus();
                    return;
                }
                //Tang so luong va thay doi tong thanh tien + Truong hop gia tien khac nhau
                if (gridChiTiet.Rows.Count > 0)
                {                    
                    for (int i = 0; i < gridChiTiet.Rows.Count; i++)
                    {
                        if (cmbMaHang.SelectedValue.ToString().Trim() == gridChiTiet.Rows[i].Cells["mamh"].Value.ToString().Trim() && txtDonGia.Text.Trim() == gridChiTiet.Rows[i].Cells["DonGia"].Value.ToString().Trim())
                        {
                            gridChiTiet.Rows[i].Cells["soluong"].Value = (int.Parse(gridChiTiet.Rows[i].Cells["soluong"].Value.ToString()) + int.Parse(txtSoluong.Text.Trim())).ToString("#,##0");
                            gridChiTiet.Rows[i].Cells["thanhtien"].Value = (int.Parse(gridChiTiet.Rows[i].Cells["soluong"].Value.ToString()) * double.Parse(gridChiTiet.Rows[i].Cells["dongia"].Value.ToString()) - int.Parse(gridChiTiet.Rows[i].Cells["soluong"].Value.ToString()) * double.Parse(gridChiTiet.Rows[i].Cells["dongia"].Value.ToString()) * double.Parse(gridChiTiet.Rows[i].Cells["chietkhau"].Value.ToString()) / 100).ToString("#,##0");
                            //Tinh tong tien hang
                            tongtienhang = 0;
                            for (int j = 0; j < gridChiTiet.Rows.Count; j++)
                            {
                                tongtienhang += double.Parse(gridChiTiet.Rows[j].Cells["ThanhTien"].Value.ToString());
                            }
                            lblTongTien.Text = tongtienhang.ToString("#,##0 VNĐ");
                            txtTongTien.Text = tongtienhang.ToString("#,##0");
                            lblTongtienChu.Text = So_chu(tongtienhang);
                            cmbMaHang.Focus();
                            return;
                        }
                    }
                }
                //Khi Mặt Hàng chưa có trong Gridview                                
                //khai bao bien
                mahang = cmbMaHang.SelectedValue.ToString();
                tenhang = txtTenHang.Text;
                dongia = txtDonGia.Text;
                soluong = txtSoluong.Text;
                khuyenmai = txtKhuyenMai.Text;
                thanhtien = txtThanhTien.Text;
                //gan gia tri cho bien
                if (gridChiTiet.Rows.Count != 0)
                    vitri = gridChiTiet.Rows.Count;
                else
                    vitri = 0;
                //them thong tin vao gridview
                gridChiTiet.Rows.AddNew();
                gridChiTiet.Rows[vitri].Cells["mamh"].Value = mahang;
                gridChiTiet.Rows[vitri].Cells["tenmh"].Value = tenhang;
                gridChiTiet.Rows[vitri].Cells["dongia"].Value = dongia;
                gridChiTiet.Rows[vitri].Cells["soluong"].Value = soluong;
                gridChiTiet.Rows[vitri].Cells["chietkhau"].Value = khuyenmai;
                gridChiTiet.Rows[vitri].Cells["thanhtien"].Value = thanhtien;
                //them mot column dang button vao gridview
                if (gridChiTiet.Columns.GetColumnByFieldName("xoa").Length == 0)
                {
                    GridViewCommandColumn btnColumn = new GridViewCommandColumn();
                    btnColumn.FieldName = "xoa";
                    btnColumn.Name = "xoa";
                    btnColumn.UseDefaultText = true;
                    btnColumn.DefaultText = "Xóa";
                    gridChiTiet.Columns.Insert(gridChiTiet.Columns.Count, btnColumn);
                }
                //Tao STT cho GridView
                if (gridChiTiet.Rows.Count > 0)
                {
                    tongtienhang = 0;                    
                    for (int i = 0; i < gridChiTiet.Rows.Count; i++)
                    {
                        gridChiTiet.Rows[i].Cells["STT"].Value = i + 1;
                        //Tinh Tong Tien
                        tongtienhang += double.Parse(gridChiTiet.Rows[i].Cells["ThanhTien"].Value.ToString());
                    }
                    lblTongTien.Text = tongtienhang.ToString("#,##0 VNĐ");
                    txtTongTien.Text = tongtienhang.ToString("#,##0");
                    lblTongtienChu.Text = So_chu(tongtienhang);
                }
                //Xoa bo thong tin trong cac o mat hang
                txtTenHang.Text = "";
                cmbMaHang.SelectedIndex = -1;
                txtSoluong.Text = "1";
                txtDonGia.Text = "0";
                txtThanhTien.Text = "0";
                txtKhuyenMai.Text = "0";
                txtTienChu.Text = "Không đồng chẳn.";
                cmbMaHang.Focus();

                //// cap nhat lai tong tien hoa don
                //tongtien += double.Parse(thanhtien.ToString());
                //txtTongTien.Text = tongtien.ToString();
                //lblTongTien.Text = tongtien.ToString();
                //lblTongtienChu.Text = "(" + So_chu(double.Parse(lblTongTien.Text)) + ")";
                ////xoa bo thong tin trong cac o
                //txtSoluong.Text = "1";
                //txtTenHang.Text = "";
                //txtDonGia.Text = "0";
                //txtKhuyenMai.Text = "";
                //txtThanhTien.Text = "0";
                //txtTienChu.Text = "không đồng";
                //cmbMaHang.SelectedIndex = -1;
                ////gan gia tri cho txt tien thoi
                //txtTienThoi.Text = txtTongTien.Text;                
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        string mahdbl = "";
        private void btnTinhTien_Click(object sender, EventArgs e)
        {
            try
            {
                errorProvider1.Clear();
                lbl_ThongBao.Text = "Thông báo!";
                if (txtChungTu.Text.Trim() == "")
                {
                    errorProvider1.SetError(txtChungTu, "Chưa nhập thông tin Số Chứng Từ.");
                    txtChungTu.Focus();
                    return;
                }
                if (mcbb_KhoHang.Text.Trim() == "")
                {
                    errorProvider1.SetError(mcbb_KhoHang, "Vui lòng chọn kho hàng.");
                    mcbb_KhoHang.Focus();
                    return;
                }
                if (Test_DMKho.Contains(mcbb_KhoHang.Text.Trim()) == false)
                {
                    errorProvider1.SetError(mcbb_KhoHang, "Kho hàng không hợp lệ.");
                    mcbb_KhoHang.Focus();
                    return;
                }
                if (dtpNgayBan.Value < DateTime.Today)
                {
                    errorProvider1.SetError(dtpNgayBan, "Ngày lập hoá đơn phải bằng hoặc lớn hơn ngày hiện tại.");
                    dtpNgayBan.Focus();
                    return;
                }
                if (gridChiTiet.Rows.Count <= 0)
                {
                    lbl_ThongBao.Text = "Chưa nhập chi tiết mặt hàng bán lẻ";
                    errorProvider1.SetError(gridChiTiet, "Chưa nhập chi tiết bán lẻ");
                    cmbMaHang.Focus();
                    return;
                }
                else
                {
                    #region "Kiem tra thông tin từng cell tren lưới"
                    for (int i = 0; i < gridChiTiet.Rows.Count; i++)
                    {
                        try
                        {
                            if (Regex.IsMatch(gridChiTiet.Rows[i].Cells["SoLuong"].Value.ToString().Trim(), @"^[0-9,',']{0,5}$") == false || int.Parse(gridChiTiet.CurrentRow.Cells["SoLuong"].Value.ToString()) < 0)
                            {
                                lbl_ThongBao.Text = "Số lượng nhập vào phải lớn hơn không (số lượng > 0) và là con số nguyên. Vui lòng nhập lại";
                                errorProvider1.RightToLeft = false;
                                return;
                            }
                            if (Regex.IsMatch(gridChiTiet.Rows[i].Cells["DonGia"].Value.ToString(), @"^[0-9,',']{0,12}$") == false)
                            {
                                lbl_ThongBao.Text = "Đơn giá nhập vào là số nguyên không âm. Vui lòng nhập lại";
                                errorProvider1.RightToLeft = false;
                                return;
                            }
                            if (Regex.IsMatch(gridChiTiet.Rows[i].Cells["Chietkhau"].Value.ToString().Trim(), @"^\d{1,2}$") == false || int.Parse(gridChiTiet.CurrentRow.Cells["ChietKhau"].Value.ToString()) > 50)
                            {
                                lbl_ThongBao.Text = "Số chiết khấu từ 0 - 50 %";
                                errorProvider1.RightToLeft = false;
                                return;
                            }
                            lbl_ThongBao.Text = "Thông báo!";
                            errorProvider1.RightToLeft = true;
                        }
                        catch (Exception ex)
                        {
                            logger.Error("Error: " + ex.Message);
                        }
                    }
                    #endregion
                }
                if (txtKhachTra.Text.Trim() == "")
                {
                    errorProvider1.SetError(txtKhachTra, "Chưa nhập tiền khách trả");
                    txtKhachTra.Focus();
                    return;
                }
                if (double.Parse(txtTongTien.Text) > double.Parse(txtKhachTra.Text))
                {
                    errorProvider1.SetError(txtKhachTra, "Khách hàng trả chưa đủ");
                    txtKhachTra.Focus();
                    return;
                }
                #region "Tinh tien  va luu thong tin"
                //tao hoa don ban le//
                mahdbl = xulyma();
                float vat = 10;
                if (!service.InsertHDBL(mahdbl, manv, mcbb_KhoHang.SelectedValue.ToString().Trim(), dtpNgayBan.Value, txtChungTu.Text, vat, double.Parse(txtTongTien.Text.ToString()), cbb_Quay.SelectedText))
                {
                    MessageBox.Show("Lưu thất bại!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                //Duyet qua Gridview de them vao bang Chi Tiet hoá đơn ban lẻ
                for (int i = 0; i < gridChiTiet.Rows.Count; i++)
                {
                    mahang = gridChiTiet.Rows[i].Cells["mamh"].Value.ToString();
                    dongia = gridChiTiet.Rows[i].Cells["dongia"].Value.ToString();
                    soluong = gridChiTiet.Rows[i].Cells["soluong"].Value.ToString();
                    khuyenmai = gridChiTiet.Rows[i].Cells["chietkhau"].Value.ToString();
                    thanhtien = gridChiTiet.Rows[i].Cells["thanhtien"].Value.ToString();
                    if (!service.InsertCTHDBL(mahang, mahdbl, double.Parse(dongia), int.Parse(soluong), float.Parse(khuyenmai), double.Parse(thanhtien)))
                    {
                        MessageBox.Show("Lưu chi tiết mặt hàng thất bại. Vui lòng gọi phòng kỹ thuật hoặc xem lại thông tin mặt hàng.", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }

                //---------------------------//
                //ghi lai vao file log hoat dong//
                logger.Debug("Nhân viên " + manv + "tạo mới hoá đơn - Ngày " + dtpNgayBan.Value.ToLongDateString());

                MessageBox.Show("Lưu hoá đơn thành công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //neu co chon in ngay//                
                if (checkbox_InHoaDonNgay.Checked == true)
                {
                    Report.frm_In_HDBL hdbl = new Report.frm_In_HDBL();
                    hdbl.mahdbl = mahdbl;
                    hdbl.ShowDialog();

                    //Tao moi Hoa don ke tiep
                    cmbMaHang.SelectedIndex = -1;
                    lblTongTien.Text = "0";
                    lblTongtienChu.Text = "(Không đồng)";
                    txtTongTien.Text = "";
                    txtTienThoi.Text = "0";
                    txtKhachTra.Text = "";
                    //thong bao thanh cong xoa cac dong trong gridview //                
                    gridChiTiet.Rows.Clear();
                }                
                #endregion
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private string xulyma()
        {
                DataSet ds_tam = new DataSet();
                string mamoi;
                string chuoi = "BL" + DateTime.Today.Year.ToString("0000") + DateTime.Today.Month.ToString("00");
                ds_tam.ReadXml(new StringReader(service.selectqueryByText("select top 1 mahdbl from hoadonbanle where mahdbl like '%" + chuoi + "%'order by mahdbl desc")));
                if (ds_tam.Tables.Count == 0)
                    mamoi = chuoi + "0001";
                else
                {
                    string matam = ds_tam.Tables[0].Rows[0][0].ToString();
                    string kituso = matam.Substring(8, 4).ToString();
                    int somoi = int.Parse(kituso) + 1;
                    mamoi = chuoi + somoi.ToString("0000");
                }
                return mamoi;
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtKhachTra_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txtKhachTra.Text.Trim() != "")
                {
                    txtKhachTra.Text = double.Parse(txtKhachTra.Text).ToString("#,##0");                    
                    double tien_ConLai = double.Parse(txtTongTien.Text) - double.Parse(txtKhachTra.Text);
                    txtTienThoi.Text = tien_ConLai.ToString("#,##0");
                }
                txtKhachTra.SelectionStart = txtKhachTra.Text.Length;
                    //tienConLai = double.Parse(txttongthanhtientinhthue.Text) - double.Parse(txtKhachTra.Text) - double.Parse(txtkhtamung.Text);
                    //txtconlai.Text = tienConLai.ToString("#,##0");
                    //}
                    //cho con tro ve cuoi textbox
                    //txtKhachTra.SelectionStart = txtKhachTra.Text.Length;

                    //txtTienThoi.Text = (double.Parse(txtKhachTra.Text) - double.Parse(txtTongTien.Text)).ToString();
                    //if (txtTienThoi.Text.Contains("-") == true)
                    //{
                    //    txtTienThoi.Text = txtTienThoi.Text.Replace("-", "");
                    //}
                
                //else
                //{
                //    txtTienThoi.Text = txtTongTien.Text;
                //}
            }
            catch (Exception ex)
            {
                logger.Error("Ham txtKhachTra_TextChanged "+ex.Message);
            }
        }

        private void gridChiTiet_CommandCellClick(object sender, EventArgs e)
        {
            double tongtien_sauxoa = 0;
            try
            {
                if (MessageBox.Show("Bạn muốn xóa chi tiết này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (gridChiTiet.Rows.Count == 1)
                    {
                        gridChiTiet.Rows.Clear();
                    }
                    else
                    {
                        gridChiTiet.Rows.RemoveAt(gridChiTiet.CurrentRow.Index);
                        for (int i = 0; i < gridChiTiet.Rows.Count; i++)
                        {
                            gridChiTiet.Rows[i].Cells["STT"].Value = i + 1;
                        }
                    }
                    for (int j = 0; j < gridChiTiet.Rows.Count; j++)
                    {
                        tongtien_sauxoa += double.Parse(gridChiTiet.Rows[j].Cells["ThanhTien"].Value.ToString());
                    }
                    lblTongTien.Text = tongtien_sauxoa.ToString("#,##0 VNĐ");
                    txtTongTien.Text = tongtien_sauxoa.ToString("#,##0");
                    lblTongtienChu.Text = So_chu(tongtien_sauxoa);                    
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void txtDonGia_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txtDonGia.Text.Length != 0)
                {
                    txtDonGia.Text = double.Parse(txtDonGia.Text).ToString("#,##0");
                    double thanhtien = double.Parse(txtSoluong.Text) * double.Parse(txtDonGia.Text) - double.Parse(txtSoluong.Text) * double.Parse(txtDonGia.Text) * float.Parse(txtKhuyenMai.Text) / 100;
                    txtThanhTien.Text = thanhtien.ToString("#,##0");
                }
                //cho con tro ve cuoi textbox
                txtDonGia.SelectionStart = txtDonGia.Text.Length;
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void txtKhuyenMai_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txtKhuyenMai.Text.Trim() != "")
                {
                    if (int.Parse(txtKhuyenMai.Text) != 0)
                    {
                        double thanhtien = double.Parse(txtSoluong.Text) * double.Parse(txtDonGia.Text) - double.Parse(txtSoluong.Text) * double.Parse(txtDonGia.Text) * float.Parse(txtKhuyenMai.Text) / 100;
                        txtThanhTien.Text = thanhtien.ToString("#,##0");
                    }
                    else
                    {
                        txtThanhTien.Text = (int.Parse(txtDonGia.Text) * int.Parse(txtSoluong.Text)).ToString("#,##0");
                    }
                }
            }
            catch
            {
            }
        }

        private void txtThanhTien_TextChanged(object sender, EventArgs e)
        {
            try
            {
                txtTienChu.Text = So_chu(double.Parse(txtThanhTien.Text));
            }
            catch { }
        }

        private void btnHuy_Click(object sender, EventArgs e)
        {
            if (gridChiTiet.Rows.Count > 0)
            {
                if (MessageBox.Show("Bạn muốn xoá mặt hàng này phải không?", "Thông Báo", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
                {
                    gridChiTiet.CurrentRow.Delete();
                }
            }
        }

        private void btn_XemIn_Click(object sender, EventArgs e)
        {
            try
            {
                //DataSet ds = new DataSet();
                //string mahdbl = "";
                //ds.ReadXml(new StringReader(service.selectqueryByText("select top 1 MaHDBL from hoadonbanle order by MaHDBL desc")));
                //if (ds.Tables.Count > 0)
                //{
                //    mahdbl = ds.Tables[0].Rows[0][0].ToString();
                //    Report.frm_In_HDBL hdbl = new Report.frm_In_HDBL();
                //    hdbl.mahdbl = mahdbl;
                //    hdbl.ShowDialog();
                //}

                Report.frm_In_HDBL hdbl = new Report.frm_In_HDBL();
                hdbl.mahdbl = mahdbl;
                hdbl.ShowDialog();

                //Tao moi Hoa don ke tiep
                cmbMaHang.SelectedIndex = -1;
                lblTongTien.Text = "0";
                lblTongtienChu.Text = "(Không đồng)";
                txtTongTien.Text = "";
                txtTienThoi.Text = "0";
                txtKhachTra.Text = "";
                //thong bao thanh cong xoa cac dong trong gridview //                
                gridChiTiet.Rows.Clear();
            }
            catch (Exception ex)
            {
            }
        }

        private void gridChiTiet_CellValueChanged(object sender, GridViewCellEventArgs e)
        {
            errorProvider1.Clear();
            try
            {
                if (Regex.IsMatch(gridChiTiet.CurrentRow.Cells["SoLuong"].Value.ToString().Trim(), @"^[0-9,',']{0,5}$") == false || int.Parse(gridChiTiet.CurrentRow.Cells["SoLuong"].Value.ToString()) < 0)
                {
                    lbl_ThongBao.Text = "Số lượng nhập vào phải lớn hơn không (số lượng > 0) và là con số nguyên. Vui lòng nhập lại";
                    errorProvider1.RightToLeft = false;                    
                    return;
                }
                if (Regex.IsMatch(gridChiTiet.CurrentRow.Cells["DonGia"].Value.ToString(), @"^[0-9,',']{0,12}$") == false)
                {
                    lbl_ThongBao.Text = "Đơn giá nhập vào là số nguyên không âm. Vui lòng nhập lại";
                    errorProvider1.RightToLeft = false;                    
                    return;
                }
                if (Regex.IsMatch(gridChiTiet.CurrentRow.Cells["Chietkhau"].Value.ToString().Trim(), @"^(\d{1,2})$") == false || int.Parse(gridChiTiet.CurrentRow.Cells["ChietKhau"].Value.ToString()) > 50)
                {
                    lbl_ThongBao.Text = "Số chiết khấu từ 0 - 50 %";
                    errorProvider1.RightToLeft = false;                 
                    return;
                }
                lbl_ThongBao.Text = "Thông báo!";
                errorProvider1.RightToLeft = true;
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void gridChiTiet_CellEndEdit(object sender, GridViewCellEventArgs e)
        {
            try
            {
                double tongtien_sausua = 0;
                double dongia = double.Parse(gridChiTiet.CurrentRow.Cells["DonGia"].Value.ToString());
                int soluong = int.Parse(gridChiTiet.CurrentRow.Cells["Soluong"].Value.ToString().Trim());
                float khuyenmai = float.Parse(gridChiTiet.CurrentRow.Cells["ChietKhau"].Value.ToString());
                double thanhtien = (soluong * dongia) - ((soluong * dongia) * khuyenmai) / 100;
                gridChiTiet.CurrentRow.Cells["ThanhTien"].Value = thanhtien.ToString("#,##0");

                for (int i = 0; i < gridChiTiet.Rows.Count; i++)
                {
                    gridChiTiet.Rows[i].Cells["SoLuong"].Value = double.Parse(gridChiTiet.Rows[i].Cells["SoLuong"].Value.ToString()).ToString("#,##0");
                    gridChiTiet.Rows[i].Cells["DonGia"].Value = double.Parse(gridChiTiet.Rows[i].Cells["DonGia"].Value.ToString()).ToString("#,##0");
                    tongtien_sausua += double.Parse(gridChiTiet.Rows[i].Cells["ThanhTien"].Value.ToString());
                    //Tinh Tong Tien                    
                }
                lblTongTien.Text = tongtien_sausua.ToString("#,##0 VNĐ");
                txtTongTien.Text = tongtien_sausua.ToString("#,##0");
                lblTongtienChu.Text = So_chu(tongtien_sausua);
            }
            catch
            {
            }
        }

        #region Lay Hinh Tu Webcam - Xu Ly Chup QR code

        #region Khai Báo Biến Load Webcame
        //Khai Bao bien lay hinh
        private const short WM_CAP = 0x400;
        private const int WM_CAP_DRIVER_CONNECT = 0x40a;
        private const int WM_CAP_DRIVER_DISCONNECT = 0x40b;
        private const int WM_CAP_EDIT_COPY = 0x41e;
        private const int WM_CAP_SET_PREVIEW = 0x432;
        private const int WM_CAP_SET_OVERLAY = 0x433;
        private const int WM_CAP_SET_PREVIEWRATE = 0x434;
        private const int WM_CAP_SET_SCALE = 0x435;
        private const int WS_CHILD = 0x40000000;
        private const int WS_VISIBLE = 0x10000000;
        private const short SWP_NOMOVE = 0x2;
        private short SWP_NOZORDER = 0x4;
        private short HWND_BOTTOM = 1;

        [DllImport("avicap32.dll")]
        protected static extern bool capGetDriverDescriptionA(short wDriverIndex,
            [MarshalAs(UnmanagedType.VBByRefStr)]ref String lpszName,
           int cbName, [MarshalAs(UnmanagedType.VBByRefStr)] ref String lpszVer, int cbVer);

        [DllImport("avicap32.dll")]
        protected static extern int capCreateCaptureWindowA([MarshalAs(UnmanagedType.VBByRefStr)] ref string
         lpszWindowName, int dwStyle, int x, int y, int nWidth, int nHeight, int hWndParent, int nID);


        [DllImport("user32")]
        protected static extern int SetWindowPos(int hwnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags);


        [DllImport("user32", EntryPoint = "SendMessageA")]
        protected static extern int SendMessage(int hwnd, int wMsg, int wParam, [MarshalAs(UnmanagedType.AsAny)] object lParam);


        [DllImport("user32")]
        protected static extern bool DestroyWindow(int hwnd);
        
        int hHwnd = 0;

        #endregion

        private void LoadDevice()
        {
            string Name = String.Empty.PadRight(100);
            string Version = String.Empty.PadRight(100);
            bool EndOfDeviceList = false;
            short index = 0;
            do
            {
                EndOfDeviceList = capGetDriverDescriptionA(index, ref Name, 100, ref Version, 100);
                index += 1;
            }
            while (!(EndOfDeviceList == false));
        }

        private void btn_LoadWebcam_Click(object sender, EventArgs e)
        {
            try
            {
                LoadDevice();
                //Dua Hinh len Picturebox
                int iHeight = pictureBox2.Height;
                int iWeight = pictureBox2.Width;
                string DeviceIndex = Convert.ToString(0);
                hHwnd = capCreateCaptureWindowA(ref DeviceIndex, WS_VISIBLE | WS_CHILD, 0, 0, 640, 480, pictureBox2.Handle.ToInt32(), 0);

                if (SendMessage(hHwnd, WM_CAP_DRIVER_CONNECT, 0, 0) != 0)
                {
                    SendMessage(hHwnd, WM_CAP_SET_SCALE, -1, 0);

                    SendMessage(hHwnd, WM_CAP_SET_PREVIEWRATE, 66, 0);

                    SendMessage(hHwnd, WM_CAP_SET_PREVIEW, -1, 0);

                    SetWindowPos(hHwnd, HWND_BOTTOM, 0, 0, pictureBox2.Width, pictureBox2.Height, SWP_NOMOVE | SWP_NOZORDER);

                }
                else
                    DestroyWindow(0);
            }
            catch { }
        }
        int demlanInQRcode = 0;
        private void btn_DocQRCode_Click(object sender, EventArgs e)
        {
            try
            {                
                IDataObject data;
                Image bmap;
                SendMessage(hHwnd, WM_CAP_EDIT_COPY, 0, 0);
                data = Clipboard.GetDataObject();

                if (data.GetDataPresent(typeof(System.Drawing.Bitmap)))
                {
                    bmap = (Image)data.GetData(typeof(System.Drawing.Bitmap));
                    //Goi Thu Vien Doc Barcode cua SDK
                    Reader reader = new Reader();
                    reader.TypeToFind = SymbologyFilter.FindQRCode;
                    reader.CustomAreaHeight = 30;
                    reader.CustomAreaWidth = 30;
                    reader.CustomAreaLeft = 30;
                    reader.CustomAreaTop = 30;
                    reader.ReadFrom((Bitmap)bmap);
                    //reader.ReadFrom(open.FileName);
                    if (reader.FoundBarcodes.Length != 0)
                    {
                        string ma_tam = "";
                        foreach (FoundBarcode barcode in reader.FoundBarcodes)
                        {
                            //cmbMaHang.Text = barcode.ToString().Substring(0, 10);
                            for (int i = 0; i < barcode.ToString().Length; i++)
                            {
                                if (barcode.ToString()[i] != '*')
                                {
                                    ma_tam += barcode.ToString()[i].ToString();
                                }
                                else
                                {
                                    i = barcode.ToString().Length;//Dung de thoat khỏi vòng lập
                                }
                            }
                            if (ma_tam != "")
                            {
                                for (int i = 0; i < cmbMaHang.EditorControl.Rows.Count; i++)
                                {
                                    //if (cmbMaHang.EditorControl.Rows[i].Cells["MaMH"].Value.ToString().Trim() == cmbMaHang.Text.Trim())
                                    if (cmbMaHang.EditorControl.Rows[i].Cells["MaMH"].Value.ToString().Trim() == ma_tam)
                                        cmbMaHang.EditorControl.Rows[i].IsCurrent = true;
                                }
                            }
                            demlanInQRcode = 0;
                            //Dong Webcam
                            SendMessage(hHwnd, WM_CAP_DRIVER_DISCONNECT, 0, 0);
                            DestroyWindow(hHwnd);
                            btnNhan.Click += new EventHandler(btnNhan_Click);//
                            return;
                        }
                    }
                    else
                    {
                        cmbMaHang.Text = "không tìm thấy";
                        demlanInQRcode++;
                        if (demlanInQRcode == 3)
                        {
                            //Dong Webcam
                            SendMessage(hHwnd, WM_CAP_DRIVER_DISCONNECT, 0, 0);
                            DestroyWindow(hHwnd);
                        }
                        
                    }
                    cmbMaHang.Focus();
                    //return;                                       
                }
            }
            catch { }
        }
        #endregion

        private void bt_home_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void bt_timkiem_Click(object sender, EventArgs e)
        {
            frmBC_ChiTietBanHang banhang = new frmBC_ChiTietBanHang();
            banhang.Show();
        }

        private void frmHoaDonBanLe_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.F2)
                txtKhachTra.Focus();
            if (e.KeyData == Keys.F5)
                btnTinhTien.Click += new EventHandler(btnTinhTien_Click);
        }




    }
}
